package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        log.info("拦截到了: {}" + request.getRequestURI());
//        long id = Thread.currentThread().getId();
//        log.info("线程id为：{}",id);

        //判断页面是否直接放行(静态资源)
        String[] urls = {
                "/backend/**",
                "/front/**",
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",
                "/user/login",
                "/user/loginout"
        };

        boolean flag = check(urls,request.getRequestURI());
       if (flag) {
           filterChain.doFilter(request, response);
           return;
       }

        //判断用户是否登录
        Long empId = (Long) request.getSession().getAttribute("employee");
        if (empId!=null) {
            BaseContext.setCurrentThread(empId);
            filterChain.doFilter(request, response);
            return;
        }

        Long user = (Long) request.getSession().getAttribute("userId");
        if (user!=null) {
            BaseContext.setCurrentThread(user);
            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录!" );
        //未登录,则返回错误信息
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));

        return;

    }
    private AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {

            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) {
                return true;
            }
        }
        return false;
    }


}
